/**
 * 商家相关接口
 * 包括新增商家、删除商家、商家列表(支持模糊)、修改商家
 */
// 引入express
const express = require("express")
// 引入数据库连接池
const pool = require("../../db/db.js")
// 引入封装后的响应结果
const Response = require("../../utils/ResponseData.js")
// 引入表单验证模块joi
const joi = require("joi")

// 创建路由
const router = express.Router()

// 商家查询接口
/**
 * 商家查询接口:http://localhost:3000/petBusiness/get?page=1&&pageSize=5&&keywords=4
 * 请求方式:get
 * 参数:req.query
 */
router.get("/petBusiness/get", async (req, res) => {
    // 表单校验
    // 配置校验规则
    console.log("进入/getBusiness", req.query);
    let schema = joi.object({
        keywords: joi.string(),//关键字,可以不传
        page: joi.number().required(),//当前页码,校验规则:必须是number,非空
        pageSize: joi.number().integer().max(10).required(),//每页显示数目 校验规则:必须是number 整数 不超过10 非空
    })
    // 校验
    let { error, value } = schema.validate(req.query)
    if (error) {
        // 校验不通过
        res.send(Response.error(error))
        return
    }
    // 校验通过
    try {
        let { page, pageSize, keywords } = req.query
        // 计算每页开始的位置=(当前页码-1)*每页显示条数
        let startIndex = (page - 1) * pageSize
        // 将pageSize转换为整数
        pageSize = pageSize ? parseInt(pageSize) : 10
        // 处理keywords
        if (!keywords) keywords = ""
        // 编写sql:查询每页显示的数据
        const sql = "select * from (select * from business where b_name like ?)b1 limit ?,?"
        // 执行sql
        const result = await pool.querySync(sql, [`%${keywords}%`, startIndex, pageSize])
        // 编写sql:查询总条数
        const sql2 = "select count(b_id) as count from (select * from business where b_name like ?)b1"
        // 执行sql
        const result2 = await pool.querySync(sql2, [`%${keywords}%`])
        // 获取查询到的总条数
        const total = result2[0].count
        // 将数据响应到前端
        res.send(Response.success({
            page: parseInt(page),
            pageSize: parseInt(pageSize),
            total,
            result,
        }))
    } catch (e) {
        res.send(Response.error(e))
    }
})

// 删除商家接口
/**
 * http://localhost:3000/petBusiness/delete?b_id=4
 * 请求方式:get
 * 参数:req.query
 */
router.get("/petBusiness/delete", (req, res) => {
    let {b_id} = req.query
    let schema = joi.object({
        b_id: joi.number().required()
    })
    let { error, value } = schema.validate(req.query)
    if (error) {
        res.send(Response.error("b_id不能为空"))
        return
    }
    const sql = "delete from business where b_id = ?"
    pool.query(sql, [b_id], (err, result) => {
        if (err) {
            res.send(Response.error("商家删除失败!"))
            console.log(err);
            return
        }
        res.send(Response.success(null, "删除成功了"))
    })
})

// 添加商家接口
/**
 * 请求url:http://localhost:3000/petBusiness/add
 * 请求方式:post
 * 参数:req.body
 */
router.post("/petBusiness/add", (req, res) => {
    // 从表单中结构数据
    let { b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer } = req.body // req.body获取表单数据,req.query获取地址栏中?key=value&&key=value
    // 封装校验规则
    let schema = joi.object({
        b_img: joi.string().required(),//字符串,非空
        b_name: joi.string().required(),//字符串,非空
        b_price: joi.number().required(),//数值,非空
        b_JS: joi.string().required(),//字符串,非空
        b_score: joi.number().required(),//数值,非空
        b_feature: joi.string().required(),//字符串,非空
        b_city: joi.string().required(),//字符串,非空
        b_city_detail: joi.string().required(),//字符串,非空
        b_offer: joi.string().required()//字符串,非空
    })
    // 校验
    let { error, value } = schema.validate(req.body)
    // 校验不通过
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 校验成功
    // 编写sql
    const sql = "insert into business(b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer)  values(?,?,?,?,?,?,?,?,?)"
    // 执行sql
    pool.query(sql, [b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer], (err, result) => {
        if (err) {
            res.send(Response.error("添加失败"))
            console.log(err);
            return
        } else {
            res.send(Response.success(null, "商家添加成功"))
        }
    })
})

// 通过id查询商家接口
/**
 * 请求url:http://localhost:3000/petBusiness/getById?b_id=4
 * 请求方式:get
 * 参数:req.query
 */
router.get("/petBusiness/getById", (req, res) => {
    let {b_id} = req.query
    let schema = joi.object({
        b_id: joi.number().required()
    })
    let { error, value } = schema.validate(req.query)
    if (error) {
        res.send(Response.error(error))
        return
    }
    const sql = "select * from business where b_id = ?"
    pool.query(sql, [b_id], (err, result) => {
        if (err) {
            res.send(Response.error("商家信息查询失败!"))
            console.log(err);
            return
        }
        if (result && result.length != 0) {
            res.send(Response.success(result[0], "商家信息查询成功!"))
        } else {
            res.send(Response.error("未查询到商家信息!"))
        }
    })
})

// 通过id修改商家信息
/**
 * 请求url:http://localhost:3000/petBusiness/update
 * 方式:post
 * 参数:req.body
 */
router.post("/petBusiness/update", (req, res) => {
    // 从表单中结构数据
    let { b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer, b_id } = req.body // req.body获取表单数据,req.query获取地址栏中?key=value&&key=value
    // 封装校验规则
    let schema = joi.object({
        b_img: joi.string().required(),//字符串,非空
        b_name: joi.string().required(),//字符串,非空
        b_price: joi.number().required(),//数值,非空
        b_JS: joi.string().required(),//字符串,非空
        b_score: joi.number().required(),//数值,非空
        b_feature: joi.string().required(),//字符串,非空
        b_city: joi.string().required(),//字符串,非空
        b_city_detail: joi.string().required(),//字符串,非空
        b_offer: joi.string().required(),//字符串,非空
        b_id: joi.number().required(),//数值,非空
    })
    // 校验
    let { error, value } = schema.validate(req.body)
    // 校验不通过
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 校验成功
    // 编写sql
    const sql = "update business set b_img=?, b_name=?, b_price=?, b_JS=?, b_score=?, b_feature=?, b_city=?, b_city_detail=?, b_offer=? where b_id = ?"
    // 执行sql
    pool.query(sql, [b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer, b_id], (err, result) => {
        console.log("-------", result);
        if (err) {
            res.send(Response.error("商家信息修改失败!"))
            return
        }
        res.send(Response.success(null, "商家信息修改成功"))
    })
})
module.exports = router